<?php

/**
 * Behavior para ajustar o formato de data
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @author        Juan Basso <jrbasso@gmail.com>
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */

/**
 * AjusteDataBehavior
 *
 * @link http://wiki.github.com/jrbasso/cake_ptbr/behavior-ajustedata
 */
class AjusteUsuariosBehavior extends ModelBehavior {

    /**
     * Configuração dos campos
     *
     * @var array
     * @access public
     */
    public $campos;

    /**
     * Setup
     *
     * @param object $model
     * @param array $config
     * @return void
     * @access public
     */
    public function setup(Model $model, $config = array()) {
        if (empty($config)) {
            // Caso n�o seja informado os campos, ele ir� buscar no schema
            $this->campos[$model->name] = $this->_buscaCamposUsuarios($model);
        } elseif (!is_array($config)) {
            $this->campos[$model->name] = array($config);
        } else {
            $this->campos[$model->name] = $config;
        }
    }

    /**
     * Before Save
     *
     * @param object $model
     * @return boolean
     * @access public
     */
    public function beforeSave(Model $model, $options = array()) {
        return $this->ajustarUsuarios($model);
    }

    /**
     * Corrigir as datas
     *
     * @param object $model
     * @return boolean
     * @access public
     */
    public function ajustarUsuarios(Model $model) {
        $data = & $model->data[$model->name];
        if(count($this->campos[$model->name]) > 0){
            $data[$this->campos[$model->name][0]] = CakeSession::read('Auth.User.id');
        }
        return true;
    }

    /**
     * Buscar campos de data nos dados da model
     *
     * @param object $model
     * @return array Lista dos campos
     * @access protected
     */
    public function _buscaCamposUsuarios(Model &$model) {
        $schema = $model->schema();
        if (!is_array($schema)) {
            return array();
        }
        $saida = array();
        if (isset($schema['usuario_id'])) {
            $saida[] = 'usuario_id';
        }
        return $saida;
    }

}
